package com.ray.validate.support.rule;

import com.ray.validate.support.utils.PropertyUtils;
import com.ray.validate.support.utils.ValidateUtil;

import javax.validation.constraints.Digits;
import java.math.BigDecimal;

/**
 * @author bo shen
 * @Description: Digits 校验
 * @Class: DigitsRule
 * @Package com.ray.validate.support.rule
 * @date 2020/3/18 9:15
 * @company <p>杭州传化陆鲸科技有限公司</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
public class DigitsRule implements Rule<Digits> {
    @Override
    public void rule(Object bean, String fieleName, Digits annotation) {
        Object value = PropertyUtils.getObjectProperty(bean, fieleName);
        if (value == null) {
            return;
        }
        BigDecimal bigNum;
        if (value instanceof BigDecimal) {
            bigNum = (BigDecimal) value;
        } else {
            bigNum = new BigDecimal(String.valueOf(value)).stripTrailingZeros();
        }
        int integerPartLength = bigNum.precision() - bigNum.scale();
        int fractionPartLength = bigNum.scale() < 0 ? 0 : bigNum.scale();
        ValidateUtil.isTrue(!(annotation.integer() >= integerPartLength && annotation.fraction() >= fractionPartLength),annotation.message());
    }

    @Override
    public void rule(Object value, Digits annotation) {
        if (value == null) {
            return;
        }
        BigDecimal bigNum;
        if (value instanceof BigDecimal) {
            bigNum = (BigDecimal) value;
        } else {
            bigNum = new BigDecimal(String.valueOf(value)).stripTrailingZeros();
        }
        int integerPartLength = bigNum.precision() - bigNum.scale();
        int fractionPartLength = bigNum.scale() < 0 ? 0 : bigNum.scale();
        ValidateUtil.isTrue(!(annotation.integer() >= integerPartLength && annotation.fraction() >= fractionPartLength),annotation.message());
    }
}
